import React, { useState, useEffect } from 'react';
import { Vector3 } from 'three';
import { Cascader, Input, Menu, Image, Button, Modal } from 'antd';
import SubMenu from 'antd/lib/menu/SubMenu';
import './index.scss';
import {
  AirFormDataLike,
  Forecast,
  cmdAirfoilAPI,
} from '../../commands/cmd-airfoil/cmdAirfoilAPI';
import { http, CSLineSegments } from '@amcax/base';
import { wsApi } from '../../../../server/wsApi';
import { ctx2, userEvents } from '../../../../module';

export default function LeftPanel() {
  /**几何信息*/
  const [airFormData, setAirFormData] = useState<AirFormDataLike>({
    camber_max: 0.02,
    camber_max_pos: 0.3,
    thickness_max: 0.12,
    thickness_max_pos: 0.3,
    leading_radius_index: 8,
    lift_angle: 0,
    mach_number: 0.785,
    reynolds_number: 5e6,
  });
  /**评估结果*/
  const [forecast, setForecast] = useState<Forecast>({
    drag: 1000.0,
    lift: 2000.1,
  });
  /**编辑状态*/
  const [isEdit, setIsEdit] = useState(false);
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [isFirstCreate, setIsFirstCreate] = useState(true);
  const [clickable, setClickable] = useState(true);
  const [predictable, setPredictable] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [dxid, setDxid] = useState(null);
  const [project_id, setProjID] = useState('');

  const edgeGroup = ctx2.cadScene.edgeGroup;

  useEffect(() => {
    // 获取 projID
    const urlParams = new URLSearchParams(window.location.search);
    const projectId = urlParams.get('doc');
    setProjID(projectId);

    // 本地储存编辑状态
    const storedState = localStorage.getItem('isEdit');
    if (storedState) {
      setIsEdit(JSON.parse(storedState));
    }

    // setTimeout(() => {
    // 判断是否已存在翼型
    console.log('edgeGroup-----leftPanel', edgeGroup.children.length);
    if (edgeGroup.children.length > 0) {
      setIsFirstCreate(false);
      setClickable(false);
      const edge = edgeGroup.children[0] as CSLineSegments;
      setDxid(edge.modelDxid);
      updateInfo();
    }
    // }, 200)
  }, []);

  /**同步表单参数 */
  const updateInfo = async () => {
    getData().then((data) => {
      const params = JSON.parse(data);
      const airformParams = {
        camber_max: params.camber_max,
        camber_max_pos: params.camber_max_pos,
        thickness_max: params.thickness_max,
        thickness_max_pos: params.thickness_max_pos,
        leading_radius_index: params.leading_radius_index,
        lift_angle: params.lift_angle,
        mach_number: params.mach_number,
        reynolds_number: params.reynolds_number,
      };
      setAirFormData(airformParams);
      const forecastParams = {
        drag: params.drag,
        lift: params.lift,
      };
      setForecast(forecastParams);
    });
  };

  /**nextCore储存数据 */
  const saveData = async () => {
    const params = {
      camber_max: airFormData.camber_max,
      camber_max_pos: airFormData.camber_max_pos,
      thickness_max: airFormData.thickness_max,
      thickness_max_pos: airFormData.thickness_max_pos,
      leading_radius_index: airFormData.leading_radius_index,
      lift_angle: airFormData.lift_angle,
      mach_number: airFormData.mach_number,
      reynolds_number: airFormData.reynolds_number,
      drag: forecast.drag,
      lift: forecast.lift,
    };
    const data = JSON.stringify(params);
    await wsApi.saveAppData(project_id, data);
  };
  /**nextCore获取数据 */
  const getData = async () => {
    return await wsApi.getAppData(project_id);
  };

  /**修改表单参数 */
  const handleAirFormDataChange = (event) => {
    let { name, value, type } = event.target;
    // console.log('e=========================', event.target)
    if (type === 'number') value = Number(value);
    if (name === 'lift_angle') {
      setPredictable(true);
    } else {
      setClickable(true);
    }
    setAirFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  /**
   * 翼型改动
   */
  const changeAirfoil = async () => {
    if (edgeGroup.children.length > 1 || isEdit) {
      setOpen(true);
    } else {
      executeCmdAirfoil();
    }
  };

  /**
   * 生成翼型
   * 请求接口 获取翼型数据 进入生成命令
   */
  const executeCmdAirfoil = async (editChange = false) => {
    setClickable(false);
    const paramData = await new Promise<Array<Vector3>>(async (resolve) => {
      // setTimeout(async () => {
      const params = {
        camber_max: airFormData.camber_max,
        camber_max_pos: airFormData.camber_max_pos,
        thickness_max: airFormData.thickness_max,
        thickness_max_pos: airFormData.thickness_max_pos,
        leading_radius_index: airFormData.leading_radius_index,
      };
      // 翼型生成
      const generateAddr = `/airfoil/v1/${project_id}/generate`;
      await http.post(generateAddr, params).then((res) => {
        // console.log('res', res)
        const jsonPoints = JSON.stringify(res.data.data);
        const pointsPos = JSON.parse(jsonPoints);
        const points3d = pointsPos.map((item) => {
          return new Vector3(item.x, item.y, 0);
        });
        resolve(points3d);
      });
    });
    const data = {
      params: paramData,
      dxid: dxid,
    };
    if (isFirstCreate) {
      await cmdAirfoilAPI.invoke(data).then((res) => {
        setDxid(res);
      });
    } else if (editChange) {
      data.dxid = null;
      await cmdAirfoilAPI.invoke(data).then((res) => {
        setDxid(res);
      });
      // 退出编辑模式
      setIsEdit(false);
      finishDraw();
      ctx2.viewer.sceneSetup.fit2DView();
      localStorage.setItem('isEdit', JSON.stringify(!isEdit));
    } else {
      cmdAirfoilAPI.invoke(data);
    }
    evaluateAirfoil();
    saveData();
  };

  /**
   * 翼型评估
   */
  const evaluateAirfoil = async () => {
    setPredictable(false);
    setUpdating(true);
    const evaluateAddr = `/airfoil/v1/${project_id}/evaluate`;
    await http.post(evaluateAddr, airFormData).then((res) => {
      // console.log('预估res====================', res)
      const jsonForecast = JSON.stringify(res.data.evaluation);
      const forecast = JSON.parse(jsonForecast);
      setForecast(forecast);
      setUpdating(false);
      setIsFirstCreate(false);
    });
  };

  /**
   * 绘制外流场
   */
  const drawOutflowField = () => {
    if (!isEdit) {
      draw();
    } else {
      finishDraw();
    }
    ctx2.viewer.sceneSetup.fit2DView();
    localStorage.setItem('isEdit', JSON.stringify(!isEdit));
  };

  const draw = async () => {
    setIsEdit(true);
    userEvents.emit('permitUndoRedo', true);
    userEvents.emit('permitCmdRectangle', true);
    ctx2.viewer.sceneSetup.resumeControl();
    await wsApi.clearUndo();
    userEvents.emit('CMD_MGR_EXECUTED', false);
  };

  const finishDraw = async () => {
    setIsEdit(false);
    userEvents.emit('permitUndoRedo', false);
    userEvents.emit('permitCmdRectangle', false);
    ctx2.viewer.sceneSetup.lockControl();
    userEvents.emit('CMD_MGR_EXECUTED', false);
  };

  /**
   * 编辑后 更新翼型提示框
   */
  const handleOk = async () => {
    setConfirmLoading(true);
    // 清除模型
    const model_dxids = [];
    for (let i = 0, l = edgeGroup.children.length; i < l; i++) {
      const edge = edgeGroup.children[i] as CSLineSegments;
      const dxid = edge.modelDxid;
      if (dxid) {
        model_dxids.push(dxid);
      }
    }
    await wsApi.delete(model_dxids);
    await executeCmdAirfoil(true);
    setConfirmLoading(false);
    setOpen(false);
  };

  const handleCancel = () => {
    setClickable(false);
    setOpen(false);
    updateInfo();
  };

  return (
    <div className='box'>
      <Menu
        defaultSelectedKeys={['999']}
        defaultOpenKeys={['sub1', 'sub2', 'sub3']}
        mode='inline'
        className='meun-panel'>
        <SubMenu
          key='sub1'
          title={<span className='menu-title'>几何信息</span>}
          className='meun-panel1'>
          <Image
            src={process.env.PUBLIC_URL + '/images/airfoil.png'}
            style={{ width: '290px' }}
          />
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>前缘半径指数(I)</div>
            <div className='input1'>
              <Input
                name='leading_radius_index'
                type='number'
                min='0.8'
                max='8.0'
                step='0.1'
                value={airFormData.leading_radius_index}
                style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                onChange={handleAirFormDataChange}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              />
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>最大厚度(T)</div>
            <div className='input1'>
              <Input
                name='thickness_max'
                type='number'
                min='0.04'
                max='0.4'
                step='0.01'
                value={airFormData.thickness_max}
                style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                onChange={handleAirFormDataChange}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              />
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>最大厚度位置(Xt)</div>
            <div className='input1'>
              <Input
                name='thickness_max_pos'
                type='number'
                min='0.2'
                max='0.6'
                step='0.1'
                value={airFormData.thickness_max_pos}
                style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                onChange={handleAirFormDataChange}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              />
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>最大弯度(F)</div>
            <div className='input1'>
              <Input
                name='camber_max'
                type='number'
                min='0'
                max='0.1'
                step='0.01'
                value={airFormData.camber_max}
                style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                onChange={handleAirFormDataChange}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              />
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>最大弯度位置(Xf)</div>
            <div className='input1'>
              <Input
                name='camber_max_pos'
                type='number'
                min='0.1'
                max='0.9'
                step='0.1'
                value={airFormData.camber_max_pos}
                style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                onChange={handleAirFormDataChange}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              />
            </div>
          </Menu.Item>
        </SubMenu>
        <div
          style={{
            display: 'flex',
            paddingTop: '10px',
            paddingBottom: '10px',
            paddingLeft: '15px',
          }}>
          <div style={{ paddingLeft: '0px', marginRight: '12px' }}>
            <Button
              type='primary'
              style={{ width: '123px', borderRadius: '10px' }}
              onClick={changeAirfoil}
              disabled={!clickable}>
              {isFirstCreate ? '生成翼型' : '更新翼型'}
            </Button>
          </div>
          <div style={{ paddingRight: '0px' }}>
            <Button
              style={{
                width: '123px',
                borderRadius: '10px',
                color: 'black',
                borderColor: '0xdadcdf',
              }}
              onClick={drawOutflowField}>
              {isEdit ? '完成绘制' : '绘制外流场'}
            </Button>
          </div>
        </div>
        <SubMenu
          key='sub2'
          title={<span className='menu-title'>翼型评估</span>}
          className='meun-panel'>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>攻角</div>
            <div className='input1'>
              <Input
                name='lift_angle'
                type='number'
                min='-5'
                max='10'
                step='1'
                value={airFormData.lift_angle}
                style={{ borderRadius: '10px', pointerEvents: 'auto' }}
                suffix={<span style={{ color: '0xdadcdf' }}>度</span>}
                onChange={handleAirFormDataChange}
                onClick={(e) => {
                  e.stopPropagation();
                }}
              />
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>马赫数</div>
            <div className='input1'>
              <div style={{ color: 'black' }}>
                {airFormData.mach_number.toExponential(2)}
              </div>
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>雷诺数</div>
            <div className='input1'>
              <div style={{ color: 'black' }}>
                {airFormData.reynolds_number.toExponential(2)}
              </div>
            </div>
          </Menu.Item>
          <div style={{ display: 'flex', justifyContent: 'center' }}>
            <Button
              type='primary'
              style={{ width: '110px', borderRadius: '10px' }}
              onClick={evaluateAirfoil}
              disabled={!predictable}>
              {'评估翼型'}
            </Button>
          </div>
        </SubMenu>
        <SubMenu
          key='sub3'
          title={
            <span className='menu-title'>
              评估结果
              {updating && <span className='menu-title'>（更新中..）</span>}
            </span>
          }
          className='meun-panel1'>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>阻力系数</div>
            <div className='input1'>
              {!isFirstCreate && (
                <div style={{ color: 'black' }}>
                  {forecast.drag.toExponential(6)}
                </div>
              )}
            </div>
          </Menu.Item>
          <Menu.Item
            className='menu-child'
            style={{ paddingLeft: '24px' }}>
            <div className='menu-child1'>升力系数</div>
            <div className='input1'>
              {!isFirstCreate && (
                <div style={{ color: 'black' }}>
                  {forecast.lift.toExponential(6)}
                </div>
              )}
            </div>
          </Menu.Item>
        </SubMenu>
      </Menu>
      <Modal
        title='修改提示'
        open={open}
        onCancel={handleCancel}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        okText='继续'
        cancelText='取消'
        style={{ borderRadius: '10px' }}>
        <p>您已进行数据编辑，重新生成翼型将清除之前数据，是否继续？</p>
      </Modal>
    </div>
  );
}
